﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Wolfy.SuperWatherService
{
    internal class Log
    {
        private static void LogStoreBuilder(string dir, out string filePath, out string currentLogTime)
        {
            if (string.IsNullOrEmpty(dir))
            {
                throw new ArgumentNullException("The path of log is null");
            }
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string fileName = DateTime.Now.ToString("yyyy_MM_dd") + ".log";
            filePath = Path.Combine(dir, fileName);
            currentLogTime = DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]");
        }
        /// <summary>
        /// 将日志写入文件
        /// </summary>
        /// <param name="dir">日志文件所在目录</param>
        /// <param name="ex">日志内容</param>
        public static void WriteLog(string dir, Exception ex)
        {
            string filePath;
            string currentLogTime;
            LogStoreBuilder(dir, out filePath, out currentLogTime);
            StringBuilder sb = new StringBuilder();
            if (ex != null)
            {

                sb.AppendLine(currentLogTime);
                //获取描述当前的异常的信息
                sb.AppendLine(ex.Message);
                //获取当前实例的运行时类型
                sb.AppendLine(ex.GetType().ToString());
                //获取或设置导致错误的应用程序或对象的名称
                sb.AppendLine(ex.Source);
                //获取引发当前异常的方法
                sb.AppendLine(ex.TargetSite.ToString());
                //获取调用堆栈上直接桢的字符串表示形式
                sb.AppendLine(ex.StackTrace);
            }
            System.IO.File.AppendAllText(filePath, sb.ToString());
        }
        public static void WriteLog(string dir, string info)
        {
            string filePath;
            string currentLogTime;
            LogStoreBuilder(dir, out filePath, out currentLogTime);
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(currentLogTime);
            sb.AppendLine(info);
            System.IO.File.AppendAllText(filePath, sb.ToString());
        }
    }
}
